<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Task as TaskModel;
use app\common\model\task\Comment;
use app\common\model\task\Star;
use app\common\model\user\School;

/**
 * 首页接口
 */
class Task extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function index()
    {
        $school_ids = School::where('user_id', $this->auth->id ?: 0)->where('status', School::STATUS_PASS)->column('school_id');
        if (!$school_ids) {
//            $this->success('', []);
        }
        $model = new TaskModel();
        $list = $model->with(['user'])->withCount(['comments', 'star'])
            ->where('audit_status', TaskModel::AUDIT_STATUS_PASS)
//            ->whereIn('company_id', $school_ids)
            ->order(['is_top' => 'desc', 'id' => 'desc'])->limit(3)->select();
        if ($list && $this->auth->id) {
            $ids = $list->column('id');
            $star = Star::whereIn('task_id', $ids)->where('user_id', $this->auth->id)->column('task_id');
            if ($star) {
                $list = $list->toArray();
                foreach ($list as &$v) {
                    if (in_array($v['id'], $star)) {
                        $v['is_star'] = 1;
                    }
                }
                unset($v);
            }
        }

        $this->success('', $list);
    }

    public function category()
    {
        $model = new \app\common\model\task\Category();
        $list = $model->order(['weigh' => 'desc', 'id' => 'desc'])
            ->field(['id', 'name'])->select();
        $this->success('', $list);
    }

    public function list()
    {
        $title = $this->request->get('title', '');
        $type_id = $this->request->get('type_id', '');
        $user_id = $this->request->get('user_id', '');

        $school_ids = School::where('user_id', $this->auth->id ?: 0)->where('status', School::STATUS_PASS)->column('school_id');
        if (!$school_ids) {
//            $this->success('', []);
        }

        $model = new TaskModel();
        $list = $model->with(['user'])->withCount(['comments', 'star'])
//            ->whereIn('company_id', $school_ids)
            ->where('audit_status', TaskModel::AUDIT_STATUS_PASS)
            ->where(function ($query) use ($title, $type_id, $user_id) {
                if ($title) {
                    $query->where('title', 'like', '%' . $title . '%');
                }
                if ($type_id) {
                    $query->where('type_id', $type_id);
                }
                if ($user_id) {
                    $query->where('user_id', $user_id);
                }
            })->order(['is_top' => 'desc', 'updatetime' => 'desc'])->select();
        if ($list && $this->auth->id) {
            $ids = $list->column('id');
            $star = Star::whereIn('task_id', $ids)->where('user_id', $this->auth->id)->column('task_id');
            if ($star) {
                $list = $list->toArray();
                foreach ($list as &$v) {
                    if (in_array($v['id'], $star)) {
                        $v['is_star'] = 1;
                    }
                }
                unset($v);
            }
        }
        $this->success('', $list);
    }

    public function auditList()
    {
        $title = $this->request->get('title', '');
        $type_id = $this->request->get('type_id', '');
        $user_id = $this->request->get('user_id', '');
        $user = \app\common\model\User::get($this->auth->id);
        if (!$user->isAdmin) {
            $this->error(__('无权限'));
        }
        $model = new TaskModel();
        $list = $model->with(['user'])
            ->where('audit_status', TaskModel::AUDIT_STATUS_WAIT)
            ->where('company_id', $user->school_id)
            ->where(function ($query) use ($title, $type_id, $user_id) {
                if ($title) {
                    $query->where('title', 'like', '%' . $title . '%');
                }
                if ($type_id) {
                    $query->where('type_id', $type_id);
                }
                if ($user_id) {
                    $query->where('user_id', $user_id);
                }
            })->order(['is_top' => 'desc', 'updatetime' => 'desc'])->select();
        if ($list && $this->auth->id) {
            $ids = $list->column('id');
            $star = Star::whereIn('task_id', $ids)->where('user_id', $this->auth->id)->column('task_id');
            if ($star) {
                $list = $list->toArray();
                foreach ($list as &$v) {
                    if (in_array($v['id'], $star)) {
                        $v['is_star'] = 1;
                    }
                }
                unset($v);
            }
        }
        $this->success('', $list);
    }

    public function auditStatus()
    {
        $id = $this->request->post('id');
        $audit_status = $this->request->post('audit_status');
        \app\common\model\Task::where('id', $id)->update([
            'audit_status' => $audit_status,
        ]);
        $this->success();
    }

    public function info()
    {
        $id = $this->request->get('id');
        if (!$id) {
            $this->error(__('Invalid parameters'));
        }
        $data = \app\common\model\Task::get($id, ['userAll', 'comments.user', 'star']);
        $data->user = $data->userAll->hidden(['password', 'salt', 'money']);
        unset($data->user_all, $data->userAll);
        $data->is_star = 0;
        $data = $data->toArray();
        if ($user_id = $this->auth->id) {
            $star = Star::where('task_id', $id)->where('user_id', $user_id)->count();
            $data['is_star'] = $star ? 1 : 0;
        }

        // 浏览量自增
        \app\common\model\Task::where('id', $id)->setInc('views');

        \app\common\model\User::where('id', $this->auth->id)->update(['school_id' => $data['company_id']]);

        $data['comments_count'] = count($data['comments'] ?: []);
        $data['star_count'] = count($data['star'] ?: []);
        unset($data['star']);
        $this->success('', $data);
    }

    public function save()
    {
        $userId = $this->auth->id;
        $type_id = $this->request->post('type_id', '');
        $title = $this->request->post('title');
        $content = $this->request->post('content');
        $images = $this->request->post('images', '');
        $location = $this->request->post('location', '');

        if (!$type_id || !$title || !$content) {
            $this->error(__('Invalid parameters'));
        }

        $user = \app\common\model\User::get($userId);

        if (\app\common\model\User::checkText($this->request->post())) {
            $this->error(__('内容包含敏感词'));
        }

        TaskModel::create([
            'user_id' => $userId,
            'company_id' => $user->school_id,
            'type_id' => $type_id,
            'title' => $title,
            'content' => $content,
            'images' => $images,
            'location' => $location,
        ]);
        $this->success();
    }

    public function update()
    {
        $userId = $this->auth->id;
        $id = $this->request->post('id');
        $type_id = $this->request->post('type_id', '');
        $title = $this->request->post('title');
        $content = $this->request->post('content');
        $images = $this->request->post('images', '');
        $location = $this->request->post('location', '');

        if (((!$type_id || !$title || !$content)) || !$id) {
            $this->error(__('Invalid parameters'));
        }

        $task = TaskModel::get($id);
        if (!$task) {
            $this->error(__('Invalid parameters'));
        }
        if ($task->user_id != $userId) {
            $this->error(__('Invalid parameters'));
        }
        if (\app\common\model\User::checkText($this->request->post())) {
            $this->error(__('内容包含敏感词'));
        }
        $task->save([
            'type_id' => $type_id,
            'title' => $title,
            'images' => $images,
            'content' => $content,
            'location' => $location,
            'audit_status' => $task->audit_status == TaskModel::AUDIT_STATUS_REFUSE ? TaskModel::AUDIT_STATUS_WAIT : $task->audit_status,
        ]);
        $this->success();
    }

    public function comment()
    {
        $userId = $this->auth->id;
        $task_id = $this->request->post('task_id', 0);
        $task_id = $task_id ? $task_id : $this->request->post('id', 0);
        $content = $this->request->post('content');

        if (!$userId || !$task_id || !$content) {
            $this->error(__('Invalid parameters'));
        }
        if (\app\common\model\User::checkText($content)) {
            $this->error(__('内容包含敏感词'));
        }
        Comment::create([
            'user_id' => $userId,
            'task_id' => $task_id,
            'content' => $content,
        ]);
        $this->success();
    }

    public function del()
    {
        $userId = $this->auth->id;
        $id = $this->request->post('id');
        if (!$id) {
            $this->error(__('Invalid parameters'));
        }

        $task = TaskModel::get($id);
        if (!$task) {
            $this->error(__('Invalid parameters'));
        }
        if ($task->user_id != $userId) {
            $this->error(__('Invalid parameters'));
        }
        $task->delete();
        $this->success();
    }

    public function star()
    {
        $userId = $this->auth->id;
        $id = (int)$this->request->post('id', 0);
        if (!$id || !TaskModel::find($id)) {
            $this->error(__('Invalid parameters'));
        }
        $map = Star::where('user_id', $userId)->where('task_id', $id)->find();
        if ($map) {
            $map->delete();
        } else {
            Star::create([
                'user_id' => $userId,
                'task_id' => $id,
            ]);
        }
        $this->success();
    }
}
